package public

import (
	"fmt"
	"go-interview-forum/pkg"
	"log"
	"mime/multipart"
	"path/filepath"
	"time"
)

var rulesMap = make(map[string]struct{})

func init() {
	rulesMap[".jpg"] = struct{}{}
	rulesMap[".png"] = struct{}{}
	rulesMap[".jpeg"] = struct{}{}
}

func UploadImage(fileInfo *multipart.FileHeader) (string, error) {
	ext := filepath.Ext(fileInfo.Filename)

	if _, ok := rulesMap[ext]; !ok {
		return "", fmt.Errorf("图片格式只能是jpg,jpeg或png")
	}

	if fileInfo.Size > 1*1024*1024 {
		return "", fmt.Errorf("图片最大1MB")
	}

	filename := time.Now().Format("20060102150405") + ext

	path, err := pkg.UploadFile(filename, fileInfo)
	if err != nil {
		log.Println(err)
		return "", fmt.Errorf("图片上传失败")
	}

	return path, nil
}
